package com.fvision.camera.view.activity;

import android.content.Intent;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.fvision.camera.BuildConfig;
import com.fvision.camera.R;
import com.fvision.camera.base.BaseActivity;
import com.fvision.camera.bean.CameraStateBean;
import com.fvision.camera.bean.FileBean;
import com.fvision.camera.iface.ICameraStateChange;
import com.fvision.camera.manager.CameraStateIml;
import com.fvision.camera.manager.CmdManager;
import com.fvision.camera.util.Cmd_Const;
import com.fvision.camera.utils.CameraStateUtil;
import com.fvision.camera.utils.LogUtils;
import com.fvision.camera.utils.ToastUtils;
import com.huiying.cameramjpeg.UvcCamera;
import com.serenegiant.usb.IFrameCallback;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

/**
 * 视频播放
 */
public class VideoPlayActivity extends BaseActivity implements View.OnClickListener {
    public static final String KEY_FILEBEAN = "KEYFILEBEAN";
    public static final String KEY_IS_LOCK = "key_is_lock";
    public static final String KEY_FILE_BEAN = "key_filebean";
    private static final int SHOW_PROGRESS = 0x10;
    private static final int HIDE_BG_FRAME = 0X11;
    private static final int SHOW_BG_FRAME = 0X12;
    private FileBean mFileBean;
    private RelativeLayout activityvideoplay;
    private TextView video_time;
    private ImageView iv_play;
    private ImageView lock;
    private SeekBar seekbar;
    private GLSurfaceView mGLSurfaceView;
    private View bg_frame;
    private UvcCamera mUvcCamera;
    private TextView play_speed;
    private boolean isDownFastButton = false;
    private int lastBtnType = -1;
    private final static int PAUSE = 0;
    private final static int PLAY = 1;
    private boolean isLock;
    ImageView rew = null;
    ImageView ffwd = null;

    private AudioTrack mAudioTrack;
    private int buf_size;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SHOW_PROGRESS:
                    break;
                case HIDE_BG_FRAME:
                    if (bg_frame != null) {
                        bg_frame.setVisibility(View.GONE);
                    }
                    break;
                case SHOW_BG_FRAME:
                    if (bg_frame != null) {
                        bg_frame.setVisibility(View.VISIBLE);
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        resetPreview(activityvideoplay);
        sendPlayCmd();
        initAudio();

        UvcCamera.getInstance().setAdasFrameCallback(new IFrameCallback() {
            @Override
            public void onFrame(byte[] frame) {
                LogUtils.d("jpeg len:" + frame.length );
            }
        });
    }

    @Override
    protected void initView() {
        this.activityvideoplay = (RelativeLayout) findViewById(R.id.activity_video_play);
        this.video_time = (TextView) findViewById(R.id.video_time);
        this.seekbar = (SeekBar) findViewById(R.id.seekbar);
        iv_play = (ImageView) findViewById(R.id.iv_play);
        this.mGLSurfaceView = (GLSurfaceView) findViewById(R.id.glsurfaceview);
        this.bg_frame = findViewById(R.id.bg_frame);
        this.play_speed = (TextView) findViewById(R.id.play_speed);
        rew = (ImageView)findViewById(R.id.rew);
        ffwd = (ImageView)findViewById(R.id.ffwd);
        lock = (ImageView) findViewById(R.id.lock);

        String deviceVersion = CmdManager.getInstance().getCurrentState().getPasswd();
        int startpos = deviceVersion.lastIndexOf("v");
        if(startpos < 0){
            return;
        }
        String str = deviceVersion.substring(startpos,startpos+4);
        LogUtils.d("version "+str + " deviceVersion "+deviceVersion);
        if(str.compareTo("v1.1") <= 0){
            rew.setVisibility(View.GONE);
            ffwd.setVisibility(View.GONE);
        }
//        String deviceVersion = "1010_v1.1";
//        float version = Float.valueOf(deviceVersion.substring(deviceVersion.length()-3,deviceVersion.length()));
//        LogUtils.d("version "+version);
//        if(version <= 1.1){
//            rew.setVisibility(View.GONE);
//            ffwd.setVisibility(View.GONE);
//        }


    }

    @Override
    protected void initData() {
        mUvcCamera = UvcCamera.getInstance();
        mFileBean = (FileBean) getIntent().getSerializableExtra(KEY_FILEBEAN);
        if(mFileBean.fileType == Cmd_Const.FILE_TYPE_LOCK || !CmdManager.getInstance().isSupportBackPlayLock()){
            lock.setVisibility(View.GONE);
        }
    }
    @Override
    protected void initListener(){
        mGLSurfaceView.setEGLContextClientVersion(2);
        mGLSurfaceView.setRenderer(new GLSurfaceView.Renderer() {
            @Override
            public void onSurfaceCreated(GL10 gl, EGLConfig config) {
                mUvcCamera.initGles(1280,720);
            }

            @Override
            public void onSurfaceChanged(GL10 gl, int width, int height) {
                UvcCamera.getInstance().changeESLayout(width, height);
            }

            @Override
            public void onDrawFrame(GL10 gl) {
                if (UvcCamera.getInstance().drawESFrame() == 0) {
                    if (bg_frame.getVisibility() == View.VISIBLE) {
                        mHandler.sendEmptyMessage(HIDE_BG_FRAME);
                    }
                }
            }
        });

        iv_play.setOnClickListener(this);
        findViewById(R.id.back).setOnClickListener(this);

        rew.setOnClickListener(this);
        ffwd.setOnClickListener(this);

        lock.setOnClickListener(this);

        CameraStateIml.getInstance().setOnCameraStateListner(new ICameraStateChange() {
            @Override
            public void stateChange() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        resrefhView();
                    }
                });
            }
        });

//        seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
//            @Override
//            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
//                LogUtils.d("progress "+progress);
//                CameraStateBean state = CmdManager.getInstance().getCurrentState();
//                if(progress == state.getTotal_time() && state.isCam_play_state()){
//
//                    LogUtils.d("播完了");
//                }
//            }
//
//            @Override
//            public void onStartTrackingTouch(SeekBar seekBar) {
//
//            }
//
//            @Override
//            public void onStopTrackingTouch(SeekBar seekBar) {
//
//            }
//        });
    }

    private void resrefhView(){
        CameraStateBean state = CmdManager.getInstance().getCurrentState();
      //  state.print();
        String totalTime = CameraStateUtil.secondToTimeString(state.getTotal_time());
        String curTime = CameraStateUtil.secondToTimeString(state.getCur_time());
        seekbar.setMax(state.getTotal_time());
        seekbar.setProgress(state.getCur_time());
        video_time.setText(curTime+"/"+totalTime);
        boolean isPlaying = state.isCam_play_state();
        iv_play.setImageResource(isPlaying?R.mipmap.preview_stop_nomal:R.mipmap.preview_play_nomal);
        if(state.getPlaySpeed() == 4 || isDownFastButton == false){
            play_speed.setVisibility(View.GONE);
        }else {
            play_speed.setVisibility(View.VISIBLE);
            play_speed.setText(formatPlaySpeed(state.getPlaySpeed()));
        }
    }

    private IFrameCallback mFrameCallback = new IFrameCallback() {
        @Override
        public void onFrame(byte[] frame) {
           // Log.e("mainactivity", "audioData " + frame.length);
            mAudioTrack.write(frame, 0, frame.length);
        }
    };

    public void initAudio() {
        UvcCamera.getInstance().setFrameCallback(mFrameCallback);

        try {
            this.buf_size = AudioTrack.getMinBufferSize(16000, 2, 2);
            this.mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 16000, AudioFormat.CHANNEL_CONFIGURATION_MONO,// 设置输出声道为双声道立体声
                    AudioFormat.ENCODING_PCM_16BIT, this.buf_size * 4, AudioTrack.MODE_STREAM);
            mAudioTrack.play();
//            Toast.makeText(getContext(),"打开audio成功",Toast.LENGTH_SHORT).show();
        } catch (Exception excetion) {
            excetion.printStackTrace();
//            Toast.makeText(getContext(),"打开audio失败:"+excetion.getMessage(),Toast.LENGTH_SHORT).show();
        }

    }

    private String formatPlaySpeed(int playSpeed){
        StringBuffer str = new StringBuffer();
        if(playSpeed < 4){
            str.append(getString(R.string.fast_back));
        }else {
            str.append(getString(R.string.fast_forward));
        }
        str.append("×");

        if(playSpeed < 4){
            str.append(""+(4 - playSpeed));
        }else {
            str.append(""+(playSpeed - 4));
        }
//        str.append(getString(R.string.times));
        return str.toString();
    }

    private void sendPlayCmd(){
        if(mFileBean == null){
            LogUtils.e("mFileBean == null");
            return;
        }
//        ToastUtils.showLongToast(getApplicationContext(),"setPlayBackFile "+mFileBean.fileIndex);
        new Thread(new Runnable() {
            @Override
            public void run() {
                CmdManager.getInstance().setPlayBackFile(mFileBean.fileName);
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                CmdManager.getInstance().playPlayBackFile();
            }
        }).start();
        CameraStateIml.getInstance().setOnCameraStateOnlyOnceListner(new ICameraStateChange() {
            @Override
            public void stateChange() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        CmdManager.getInstance().playPlayBackFile();
                    }
                }).start();
            }
        });
    }

    private void startCamera(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (!mUvcCamera.isInit()) {
                    mUvcCamera.setPkgName(BuildConfig.APPLICATION_ID);
                    mUvcCamera.initUvccamera();
                }
                if (mUvcCamera.isInit()) {
                    if (!mUvcCamera.isPreviewing())
                        mUvcCamera.startPreview();
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        }).start();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mAudioTrack.stop();
        mAudioTrack.release();
        new Thread(new Runnable() {
            @Override
            public void run() {
                CmdManager.getInstance().pausePlayBackFile();
            }
        }) .start();

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_video_play;
    }

    @Override
    protected void init() {

    }

    private void togglePlay(){
        final boolean isPlaying = CmdManager.getInstance().getCurrentState().isCam_play_state();
        new Thread(new Runnable() {
            @Override
            public void run() {
                if(isPlaying){
                    lastBtnType = PAUSE;
                    CmdManager.getInstance().pausePlayBackFile();
                }else{
                    if(seekbar.getProgress() == 0){
                        isDownFastButton = false;
                        CmdManager.getInstance().setPlayBackFile(mFileBean.fileName);
                    }
                    lastBtnType = PLAY;
                    CmdManager.getInstance().playPlayBackFile();
                }
            }
        }).start();
        //规避回放结束之后，需要点两次播放按钮才能播放的问题
        CameraStateIml.getInstance().setOnCameraStateOnlyOnceListner(new ICameraStateChange() {
            @Override
            public void stateChange() {
                boolean isPlaying = CmdManager.getInstance().getCurrentState().isCam_play_state();
                int sava_1 = CmdManager.getInstance().getCurrentState().getSave_1();
                if(lastBtnType == PLAY && !isPlaying && sava_1 == Cmd_Const.CAM_SET_PLAY){
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            CmdManager.getInstance().playPlayBackFile();
                        }
                    }).start();
                }
            }
        });
    }

    private void lock(){
        if(isLock){
            return;
        }
        if(CmdManager.getInstance().lockBackPlay(mFileBean.fileName)){
            ToastUtils.showLongToast(getApplicationContext(),getString(R.string.lock_success));
            lock.setBackgroundResource(R.mipmap.lock_press);
            isLock = true;
        }else {
            isLock = false;
            ToastUtils.showLongToast(getApplicationContext(),getString(R.string.lock_fail));
        }
    }

    private void back(){
        Intent intent = new Intent(VideoPlayActivity.this, PlaybackActivity.class);
        intent.putExtra(KEY_IS_LOCK, isLock);
        intent.putExtra(KEY_FILE_BEAN,mFileBean);
        setResult(PlaybackActivity.REQUEST_VIDEO_PLAY, intent);
        finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_play:
                togglePlay();
                break;
            case R.id.back:
                back();
                break;
            case R.id.rew:
                isDownFastButton = true;
                CmdManager.getInstance().fastBackward();
//                if (current_speed > MIN_SPEED) {
//                    current_speed--;
//                }
//                Toast.makeText(mContext, String.format("%dX", current_speed), Toast.LENGTH_SHORT).show();
                break;
            case R.id.ffwd:
                isDownFastButton = true;
                CmdManager.getInstance().fastForward();
//                if (current_speed < MAX_SPEED) {
//                    current_speed++;
//                }
//                Toast.makeText(mContext, String.format("%dX", current_speed), Toast.LENGTH_SHORT).show();
                break;
            case R.id.lock:
                lock();
                break;
        }
    }
}
